package cn.tedu.straw.portal.controller;


import cn.tedu.straw.portal.dto.PostAnswerDTO;
import cn.tedu.straw.portal.ex.InvalidParameterException;
import cn.tedu.straw.portal.security.LoginUserInfo;
import cn.tedu.straw.portal.service.IAnswerService;
import cn.tedu.straw.portal.util.R;
import cn.tedu.straw.portal.vo.AnswerListItemVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2020-11-11
 */
@RestController
@RequestMapping("/portal/answer")
@Slf4j
public class AnswerController {

    @Autowired
    IAnswerService answerService;

    // http://localhost:8080/portal/answer/post?questionId=1&content=TestAnswer2
    @RequestMapping("/post")
    public R<Void> post(@Valid PostAnswerDTO postAnswerDTO, BindingResult bindingResult,
                        @AuthenticationPrincipal LoginUserInfo loginUserInfo) {
        log.debug("发表答案，客户端提交的数据：{}", postAnswerDTO);
        log.debug("发表答案，当前登录的用户信息：{}", loginUserInfo);

        if (bindingResult.hasErrors()) {
            String errorMessage = bindingResult.getFieldError().getDefaultMessage();
            throw new InvalidParameterException(errorMessage);
        }

        Integer userId = loginUserInfo.getUserId();
        String userNickName = loginUserInfo.getNickName();
        answerService.post(postAnswerDTO, userId, userNickName);
        return R.ok();
    }

    // http://localhost:8080/portal/answer?questionId=4
    @GetMapping("")
    public R<List<AnswerListItemVO>> getAnswerList(Integer questionId) {
        return R.ok(answerService.getAnswerList(questionId));
    }

}
